#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
class TcpClient
{
  private:
    int port;
    std::string ip;
    int sockfd;
  public:
    TcpClient(int _port,std::string _ip):port(_port),ip(_ip),sockfd(-1)
    {}
    ~TcpClient()
    {
      if(sockfd>=0)close(sockfd);
    }
    void InitTcpClient()
    {
      sockfd=socket(AF_INET,SOCK_STREAM,0);
      if(sockfd<0)
      {
        std::cerr<<"socket error"<<std::endl;
        exit(2);
      }
    }
    void Start()
    {
      struct sockaddr_in peer;
      memset(&peer,0,sizeof(peer));
      peer.sin_family=AF_INET;
      peer.sin_port=htons(port);
      peer.sin_addr.s_addr=inet_addr(ip.c_str());

      if(connect(sockfd,(struct sockaddr*)&peer,sizeof(peer))==0)
      {
        std::cout<<"connect success"<<std::endl;
        Request();
      }else 
      {
        std::cerr<<"connect error"<<std::endl;
      }
    }
    void Request()
        {
            std::string message;
            char buffer[1024];
            while(true){
                std::cout << "Please Enter# ";
                std::cin >> message;

                write(sockfd, message.c_str(), message.size());

                ssize_t s = read(sockfd, buffer, sizeof(buffer)-1);
                if(s > 0) buffer[s] = 0;

                std::cout << "server echo# " << buffer << std::endl;
            }
        }
};
